﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.Contracts.Report;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.App;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System.ComponentModel;

namespace PoorderBillFXMX
{
    [Description("采购统计分析明细服务插件")]
    [Kingdee.BOS.Util.HotUpdate]
    public class MXFService : SysReportBaseService
    {
        #region 临时表定义
        //临时表集合
        private List<string> tempTable = new List<string>();
        //接存储过程的临时表
        private string T_Temp_First = string.Empty;
        //最终数据表
        private string T_Temp_Last = string.Empty;
        //自己创建的临时表的SQL语句 List
        List<SqlObject> listTableSqlObj = new List<SqlObject>();

        #endregion

        #region 报表加载初始化
        public override void Initialize()
        {
            base.Initialize();
            this.ReportProperty.ReportType = ReportType.REPORTTYPE_NORMAL;
            this.ReportProperty.ReportName = new LocaleValue("采购统计分析明细查询", this.Context.UserLocale.LCID);
            this.ReportProperty.SimpleAllCols = true;
            this.ReportProperty.IsGroupSummary = true; // 支持分组汇总

            //this.ReportProperty.DecimalControlFieldList = new List<DecimalControlField>();
            //// 标示famount用famount_decimal做精度格式化
            //this.ReportProperty.DecimalControlFieldList.Add(new DecimalControlField() { ByDecimalControlFieldName = "famount", DecimalControlFieldName = "famount_decimal" });

        }
        #endregion

        public override Kingdee.BOS.Core.Report.ReportTitles GetReportTitles(Kingdee.BOS.Core.Report.IRptParams filter)
        {
            string FORGName, FSDate, FEndate;

            ReportTitles titles = new ReportTitles();
            DynamicObject dyFilter = filter.FilterParameter.CustomFilter;

            DynamicObject FORG = dyFilter["FSUBORGID"] as DynamicObject;
            FORGName = Convert.ToString(FORG["Name"]);

            FSDate = Convert.ToString(dyFilter["FSDate"]);

            FEndate = Convert.ToString(dyFilter["FEDate"]);

            titles.AddTitle("FSUBORGID", FORGName);
            titles.AddTitle("FSDate", FSDate);
            titles.AddTitle("FEdate", FEndate);

            return titles;
        }

        public override Kingdee.BOS.Core.Report.ReportHeader GetReportHeaders(Kingdee.BOS.Core.Report.IRptParams filter)
        {
            ReportHeader header = new ReportHeader();

            header.AddChild("FSupNo", new LocaleValue("供应商", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FSupName", new LocaleValue("供应商名称", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FDate", new LocaleValue("采购订单日期", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FBILLNO", new LocaleValue("采购订单编号", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);           
            header.AddChild("FALLAMOUNT", new LocaleValue("订单金额", this.Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("FGBAmount", new LocaleValue("关闭订单金额", this.Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("FSJCG", new LocaleValue("实际采购金额", this.Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("FREALPAYAMOUNT", new LocaleValue("付款(退款)金额", this.Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("FDISCOUNTAMOUNTFOR", new LocaleValue("折扣额", this.Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("FSJFJAmount", new LocaleValue("实际应付款金额", this.Context.UserLocale.LCID), SqlStorageType.SqlDecimal);


            return header;

        }

        public override void BuilderReportSqlAndTempTable(Kingdee.BOS.Core.Report.IRptParams filter, string tableName)
        {
            DynamicObject dyFilter = filter.FilterParameter.CustomFilter;
            //创建所需临时表
            CreatBillDataFirstTempTable(filter);
            T_Temp_Last = tableName;  //获得最终返回数据临时表名
            //执行建表语句
            DBUtils.ExecuteBatch(this.Context, listTableSqlObj);
            listTableSqlObj.Clear();
            //把存储过程里的数据插入临时表里
            InsertFirstTempTable(this.Context, filter);

            //最后再把数导入到最后的返回表里
            string sSQL = @"/*dialect*/ select a.* , {0}  into {1} from " + this.T_Temp_First + " a " + " order by FBILLNO";
            KSQL_SEQ = string.Format(KSQL_SEQ, "FBillNo");
            sSQL = string.Format(sSQL, this.KSQL_SEQ, tableName);
            DBUtils.Execute(this.Context, sSQL);
            this.DeleteTempTable();   //删除临时表
        }


        /// <summary>
        /// 创建临时表用来接后台存储过程传过来的数据，因为有动态列所以还需要传一下过滤条件
        /// </summary>
        private void CreatBillDataFirstTempTable(IRptParams filter)
        {
            StringBuilder sbSql = new StringBuilder();
            IDBService service = ServiceHelper.GetService<IDBService>();
            T_Temp_First = service.CreateTemporaryTableName(this.Context);
            sbSql.AppendFormat(@"CREATE TABLE {0}
                                   (FSupNo nvarchar(500) default '',
                                    FSupName nvarchar(500) default '',
                                    FDate nvarchar(500) default '',
                                    FBillNo nvarchar(500) default '',
                                    FALLAMOUNT decimal(19,2) default 0,
                                    FGBAmount decimal(19,2) default 0,
                                    FSJCG decimal(19,2) default 0,
                                    FREALPAYAMOUNT decimal(19,2) default 0,
                                    FDISCOUNTAMOUNTFOR decimal(19,2) default 0,
                                    FSJFJAmount decimal(19,2) default 0
                                     ) ", T_Temp_First);
            listTableSqlObj.Add(new SqlObject(sbSql.ToString(), new List<SqlParam>()));
            //记录自己创建的临时表
            tempTable.Add(T_Temp_First);
            sbSql.Clear();
        }


        /// <summary>
        /// 根据过滤条件获得执行存储过程的参数
        /// </summary>
        private string GetSpParams(IRptParams filter)
        {
            string FSUBORGID, FSDate, FEndate, FSupName = "",  FBillNo;
            string FSupWHERE = "", FPOWHERE="";


            ReportTitles titles = new ReportTitles();
            DynamicObject dyFilter = filter.FilterParameter.CustomFilter;

            DynamicObject FORG = dyFilter["FSUBORGID"] as DynamicObject;
            FSUBORGID = Convert.ToString(FORG["id"]);


            DynamicObject FSup = dyFilter["FSupName"] as DynamicObject;
            if (FSup != null)
            {
                FSupName = Convert.ToString(FSup["Name"]);
                FSupWHERE = "and  SUPNa.FNAME =''" + FSupName + " ''"; ;
            }
            else if (FSup == null)
            {
                FSupWHERE = "and 1=1"; ;
            }


            FSDate = Convert.ToString(dyFilter["FSDate"]);

            FEndate = Convert.ToString(dyFilter["FEDate"]);


            FBillNo = Convert.ToString(dyFilter["FPOBillNo"]);
            if (FBillNo != "")
            {
                FPOWHERE = "and PO.FBillNo like ''%" + FBillNo + "%''";
            }
            else if (FBillNo == "")
            {
                FPOWHERE = "and 1=1";
            }

           

            return "'" + FSDate + "', '" + FEndate + "',  '" + FSUBORGID + "','" + FSupWHERE + "','" + FPOWHERE + "'";
        }

        /// <summary>
        /// 填充数据到最终的临时表里
        /// </summary>
        private void InsertFirstTempTable(Context ctx, IRptParams filter)
        {
            StringBuilder sql = new StringBuilder();

            //这个时候还没有返回表呢,先创建一下吧 

            sql.Append("/*dialect*/ INSERT INTO " + T_Temp_First);
            sql.Append("  exec BT_POOrTJMX " + GetSpParams(filter));

            DBUtils.Execute(ctx, sql.ToString());
            sql.Clear();
        }

        /// <summary>
        /// 删除临时表操作
        /// </summary>
        public void DeleteTempTable()
        {
            IDBService service = Kingdee.BOS.App.ServiceHelper.GetService<IDBService>();
            if (this.tempTable.Count > 0)
            {
                //删除临时表
                service.DeleteTemporaryTableName(this.Context, this.tempTable.ToArray());
                this.tempTable.Clear();
            }
        }

        /// <summary>
        /// 设置报表合计列
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public override List<SummaryField> GetSummaryColumnInfo(IRptParams filter)
        {
            var result = base.GetSummaryColumnInfo(filter);
            result.Add(new SummaryField("FALLAMOUNT", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("FGBAmount", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("FSJCG", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("FREALPAYAMOUNT", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("FDISCOUNTAMOUNTFOR", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("FSJFJAmount", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));

            return result;
        }
    }
}
